<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.25" charset="UTF-8">
    <title>Cart</title>
    <link rel="StyleSheet" href="/css/jpetstore.css" type="text/css" media="screen"/>
</head>

<body>
<div th:replace="common/top"></div>
<div id="BackLink">
    <a href="mainForm">Return to Main Menu</a>
</div>

<div id="Catalog">
    <div id="Cart">
        <h2>Shopping Cart</h2>

        <!--<form action="@{/catalog/updateCart(cartItems=${session.cart.cartItems})}" method="post">-->
        <form th:action="@{/catalog/updateCart}" method="post">
            <input type="hidden" name="cartItems" th:value="${session.cart.cartItems}"/>
        </form>

        <table>
                <tr>
                    <th><b>Item ID</b></th>
                    <th><b>Product ID</b></th>
                    <th><b>Description</b></th>
                    <th><b>In Stock?</b></th>
                    <th><b>Quantity</b></th>
                    <th><b>List Price</b></th>
                    <th><b>Total Cost</b></th>
                    <th>&nbsp;</th>
                </tr>

                <tr th:if="${session.cart.getNumberOfItems() == 0}">
                    <td colspan="8"><b>Your cart is empty.</b></td>
                </tr>

                <tr th:each="cartItem:${session.cart.cartItems}" th:id="${cartItem.item.itemId}">
                    <td>
                        <a th:href="@{/catalog/viewItem(itemId=${cartItem.item.itemId})}" th:text="${cartItem.item.itemId}">
                            Item ID
                        </a>
                    </td>
                    <td th:text="${cartItem.item.productId}">
                        Product ID
                    </td>


                    <td th:text="${#strings.defaultString(cartItem.item.attribute1, '')} + ' ' +
             ${#strings.defaultString(cartItem.item.attribute2, '')} + ' ' +
             ${#strings.defaultString(cartItem.item.attribute3, '')} + ' ' +
             ${#strings.defaultString(cartItem.item.attribute4, '')} + ' ' +
             ${#strings.defaultString(cartItem.item.attribute5, '')} + ' ' +
             ${cartItem.item.productId}">Description
                    </td>
                    <td th:text=" 'yes'">
                        In Stock?
                    </td>

                    <td>
                        <input type="number"
                               min="0"
                               th:id="${cartItem.item.itemId}"
                               th:name="${cartItem.item.itemId}"
                               th:value="${cartItem.quantity}"
                               onchange="changeCart('${cartItem.item.itemId}', this.value)"
                        class="quantity-input">
                        <div th:if="${cartItem.quantity <= 0}"
                             class="error-msg"
                             th:text="'最少购买1件'">
                        </div>
                    </td>


                    <!-- 单价显示 -->
                    <td th:text="'$' + ${#numbers.formatDecimal(cartItem.item.listPrice, 1, 2, 'POINT')}"
                        th:id="|${cartItem.item.itemId}Price|">
                    </td>

                    <!-- 总价显示 -->
                    <td th:id="${cartItem.item.itemId} + 'Total'"
                        th:text="'$' + ${#numbers.formatDecimal(cartItem.total, 1, 2, 'POINT')}">
                    </td>
                    <td style="min-width: 120px">
                        <a class="Button" th:href="@{/catalog/remove(itemId=${cartItem.item.itemId})}">
                            Remove
                        </a>
                    </td>
                </tr>

                <tr>
                    <td colspan="7">Sub Total:
                        <label id="total" th:text="'$'+${#numbers.formatDecimal(session.cart.subTotal, 1,2)}">
                        </label>
                    </td>
                </tr>
                <tr>
                    <td colspan="8" style="text-align: right">
                        <a th:href="@{/order/new}" class="Button">Proceed to Checkout</a>
                        <form th:action="@{/order/submit}" method="post">
                            <input type="submit" value="Confirm Order" class="Button"/>
                        </form>
                    </td>
                </tr>


            </table>
        </form>

        <P  id="demo"></P>

    </div>

    <div id="MyList">
    </div>

    <div id="Separator">&nbsp;</div>
</div>

<div th:replace="common/bottom"></div>

<!--脚本-->
<script th:src="@{/js/background.js}" count="500"></script>


<script>

    function parsePrice(priceStr) {
        // 正确处理示例：
        // "$1,500.50" → 1500.50
        // "$15.50" → 15.50
        return parseFloat(
            priceStr
                .replace('$', '')    // 移除货币符号
                .replace(/,/g, '')   // 移除千分位逗号
        );
    }

    // 更新单个商品总价和购物车小计
    function changeCart(itemId, newQuantity) {
        // 1. 输入验证
        const quantity = parseInt(newQuantity);
        const inputElement = document.getElementById(itemId);
        if (quantity < 1) {
            inputElement.setCustomValidity("数量不能小于1");
            inputElement.reportValidity();
            inputElement.value = 1; // 自动重置为合法值
            return;
        }
        if (isNaN(quantity)){
            alert("请输入有效数字");
            return;
        }

        // 2. 安全获取价格元素
        const priceElement = document.getElementById(`${itemId}Price`);
        if (!priceElement) {
            console.error(`找不到价格元素：${itemId}Price`);
            return;
        }

        // 3. 提取价格数值
        const priceStr = priceElement.textContent;
        const unitPrice = parsePrice(priceElement.textContent);

        // 4. 计算并更新总价
        const totalElement = document.getElementById(`${itemId}Total`);
        if (!totalElement) {
            console.error(`找不到总价元素：${itemId}Total`);
            return;
        }
        totalElement.textContent = `$${(unitPrice * quantity).toFixed(2)}`;

        // 5. 更新小计
        updateSubTotal();

        // 6. 发送异步请求到后端更新Session
        const formData = new FormData();
        formData.append('itemId', itemId);
        formData.append('quantity', quantity);

        fetch('/catalog/updateCartItem', {
            method: 'POST',
            body: formData
        }).then(response => {
            if (!response.ok) throw new Error('更新失败');
        }).catch(error => {
            console.error('保存失败:', error);
            alert('自动保存失败，请手动刷新页面');
        });
    }

    // 添加页面卸载事件监听
    window.addEventListener('beforeunload', function(e) {
        // 遍历所有输入框同步数据
        document.querySelectorAll('.quantity-input').forEach(input => {
            const itemId = input.id;
            const quantity = input.value;

            // 同步发送请求（使用同步XHR）
            const xhr = new XMLHttpRequest();
            xhr.open('POST', '/catalog/updateCartItem', false); // 同步请求
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.send(`itemId=${encodeURIComponent(itemId)}&quantity=${encodeURIComponent(quantity)}`);
        });
    });


    // 计算并更新购物车小计
    function updateSubTotal() {
        let subTotal = 0;

        // 遍历所有总价单元格
        document.querySelectorAll("[id$='Total']").forEach(element => {
            if (element.id !== "total") { // 排除小计本身
                const price = parseFloat(
                    element.textContent
                        .replace('$', '')
                        .replace(/,/g, '')
                );
                subTotal += price;
            }
        });

        // 更新小计显示
        document.getElementById("total").textContent =
            `$${subTotal.toFixed(2)}`;
    }


    document.addEventListener('change', function(e) {
        if (e.target.classList.contains('quantity-input')) {
            const itemId = e.target.id;
            const newQuantity = e.target.value;
            changeCart(itemId, newQuantity);
        }
    });
</script>
</body>
</html>
